package com.backend.controller.rbac;

import com.backend.annotation.RequireRole;
import com.backend.service.rbac.AuthService;
import com.common.constant.MessageConstant;
import com.common.result.Result;
import com.pojo.dto.AuthDTO;
import com.pojo.vo.AuthVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    AuthService authService;
    /**
     * 增加一个权限
     */
    @PostMapping("/insertAuth")
    @RequireRole("admin")
    public Result insertAuth(@RequestBody AuthDTO authDTO) {
        authService.insertAuth(authDTO);
        return Result.success(MessageConstant.AUTH_INSERT_SUCCESS);
    }
    /**
     * 通过name删除一个权限
     */
    @DeleteMapping("/removeAuth/{name}")
    @RequireRole("admin")
    public Result removeAuth(@PathVariable("name") String name) {
        Integer result = authService.removeAuth(name);
        if (result == 0) {
            return Result.error(MessageConstant.AUTH_DELETE_FAIL);
        }
        return Result.success(MessageConstant.AUTH_DELETE_SUCCESS);
    }
    /**
     * 更新权限内容
     */
    @PutMapping("/updateAuth")
    @RequireRole("admin")
    public Result updateAuth(@RequestBody AuthDTO authDTO) {
        Integer result = authService.updateAuth(authDTO);
        if (result == 0) {
            return Result.error(MessageConstant.UPDATE_AUTH_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_AUTH_SUCCESS);
    }
    /**
     * 通过权限名查询权限
     */
    @GetMapping("/getAuthByName/{name}")
    @RequireRole("admin")
    public Result getAuthByName(@PathVariable("name") String name) {
        AuthVO authVO = authService.getAuthByName(name);
        if (authVO == null) {
            return Result.error("没有名为" + name + "的权限");
        }
        return Result.success(authVO);
    }
    /**
     * 查询所有权限
     */
    @GetMapping("/getAllAuth")
    @RequireRole("admin")
    public Result getAllAuth() {
        List<AuthVO> authVOS = authService.getAllAuth();
        return Result.success(authVOS);
    }
    /**
     * 修改权限的状态
     */
    @PutMapping("/updateAuthStatus/{status}/{id}")
    @RequireRole("admin")
    public Result updateAuthStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Integer result = authService.updateAuthStatus(id, status);
        if (result == 0) {
            return Result.error(MessageConstant.UPDATE_AUTH_STATUS_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_AUTH_STATUS_SUCCESS);
    }
}
